package com.lxd.sunso.product.service.impl;

import com.lxd.sunso.common.utils.PageUtils;
import com.lxd.sunso.common.utils.Query;
import com.lxd.sunso.product.entity.DatatemplateEntity;
import com.lxd.sunso.product.entity.MachineEntity;
import com.lxd.sunso.product.service.DatatemplateService;
import com.lxd.sunso.product.service.MachineService;
import com.lxd.sunso.product.vo.TemplateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxd.sunso.product.dao.TemplateDao;
import com.lxd.sunso.product.entity.TemplateEntity;
import com.lxd.sunso.product.service.TemplateService;


@Service("templateService")
public class TemplateServiceImpl extends ServiceImpl<TemplateDao, TemplateEntity> implements TemplateService {

    @Autowired
    private MachineService machineService;

    @Autowired
    private DatatemplateService datatemplateService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TemplateEntity> page = this.page(
                new Query<TemplateEntity>().getPage(params),
                new QueryWrapper<TemplateEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void removetemplate(List<Long> asList) {
        //删除所有的dataTemplate
        for (Long templateId : asList) {
            datatemplateService.remove(new QueryWrapper<DatatemplateEntity>().eq("TemplateID", templateId));
            List<MachineEntity> entities = machineService.list(new QueryWrapper<MachineEntity>().eq("TemplateID", templateId));
            if (entities != null && entities.size() > 0) {
                List<Long> machineIds = entities.stream().map(entity -> {
                    return entity.getId();
                }).collect(Collectors.toList());
                if (machineIds != null && machineIds.size() > 0) {
                    machineService.delete(machineIds);
                }
            }
        }
        this.removeByIds(asList);
    }

    @Override
    public List<TemplateVo> getTemNameAndId() {
        List<TemplateEntity> list = this.list();
        List<TemplateVo> collect = list.stream().map(entity -> {
            TemplateVo templateVo = new TemplateVo();
            BeanUtils.copyProperties(entity, templateVo);
            return templateVo;
        }).collect(Collectors.toList());
        return collect;
    }
}